package videostoreapp;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.naming.InitialContext;


import org.apache.derby.jdbc.ClientDataSource;

public class Constants {

    //public static String dbConn = "jdbc:derby://localhost:1527/vidsvc;user=app;password=app";
    public static ClientDataSource ds = null;

    static {
        ds = new org.apache.derby.jdbc.ClientConnectionPoolDataSource();
        ds.setPortNumber(1527);
        ds.setServerName("localhost");
        ds.setDatabaseName("vidsvc");
        ds.setUser("app");
        ds.setPassword("app");


    }

    public static Connection getConnection() throws SQLException {
        Connection conn = ds.getConnection();
        conn.setAutoCommit(true);
        return conn;
    }

    public static void SQLExceptionHandler(SQLException sqe) {
        try {
            System.err.println(sqe.getMessage());
            System.exit(1);
        } catch (Exception ex) {
            Logger.getLogger(Constants.class.getName()).log(Level.SEVERE, null, ex);
        }
        sqe.printStackTrace();
    }

    public static ConnectionFactory getOrderConnectionFactory() throws Exception {
        InitialContext ic = getInitialContext();
        return (ConnectionFactory) ic.lookup("jms/OrderConnectionFactory");
    }

    public static Queue getOrderQueue() throws Exception {
        InitialContext ic = getInitialContext();
        return (Queue) ic.lookup("jms/OrderQueue");

    }

    public static ConnectionFactory getDeliveryConnectionFactory() throws Exception {
        InitialContext ic = getInitialContext();
        return (ConnectionFactory) ic.lookup("jms/DeliveryConnectionFactory");
    }

    public static Queue getDeliveryQueue() throws Exception {
        InitialContext ic = getInitialContext();
        return (Queue) ic.lookup("jms/DeliveryQueue");

    }

    private static InitialContext getInitialContext() throws Exception {

        Properties props = new Properties();
        props.setProperty("java.naming.factory.initial",
                "com.sun.enterprise.naming.SerialInitContextFactory");
        props.setProperty("java.naming.factory.url.pkgs",
                "com.sun.enterprise.naming");
        props.setProperty("java.naming.factory.state",
                "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");

        // optional.  Defaults to localhost.  Only needed if web server is running
        // on a different host than the appserver
        props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");

        // optional.  Defaults to 3700.  Only needed if target orb port is not 3700.
        props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");


        InitialContext ic = new InitialContext(props);

        return ic;
    }
}
